package design.p12_flyWeight;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: Java
 * @description:
 * @author: zxf
 * @create: 2021-06-18 18:59
 **/
public class ConnectionPool {

    private List<Connection> pool;

    private String url = "";
    private String username = "";
    private String password = "";
    private String driverClassName = "";

    private Connection conn = null;
    private int poolSize = 10;

    // 饿汉单例模式
    public static ConnectionPool connectionPool = new ConnectionPool();

    private ConnectionPool(){
        pool = new ArrayList<>();
        for (int i = 0; i  < poolSize; i++){
            try {
                Class.forName(driverClassName);
                conn = DriverManager.getConnection(url,username,password);
                pool.add(conn);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public static ConnectionPool getConnectionPool(){
        return connectionPool;
    }
    public synchronized void release(){
        pool.add(conn);
    }

    public synchronized Connection getConnection() throws Exception {
        if (pool.size() <= 0) {
            throw new Exception("没有空闲的连接~~~");
        }
        Connection connection = pool.get(0);
        pool.remove(connection);
        return connection;
    }

    public static void main(String[] args) {
        ConnectionPool connectionPool = ConnectionPool.getConnectionPool();
        try {
            connectionPool.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

